import { useUserStore } from '@/store/user'

/**
 * 权限指令
 * 使用方式：
 * v-permission="'user:edit'"
 * v-permission="['user:edit', 'user:delete']"
 * v-permission-role="'ADMIN'"
 * v-permission-role="['ADMIN', 'SUPER_ADMIN']"
 */

export const permission = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const userPermissions = userStore.userInfo?.permissions || []
    
    if (value) {
      const permissions = Array.isArray(value) ? value : [value]
      const hasPermission = permissions.some(permission => 
        userPermissions.includes(permission)
      )
      
      if (!hasPermission) {
        el.parentNode?.removeChild(el)
      }
    }
  }
}

export const permissionRole = {
  mounted(el, binding) {
    const { value } = binding
    const userStore = useUserStore()
    const userRoles = userStore.userInfo?.roles || []
    
    if (value) {
      const roles = Array.isArray(value) ? value : [value]
      const hasRole = roles.some(role => userRoles.includes(role))
      
      if (!hasRole) {
        el.parentNode?.removeChild(el)
      }
    }
  }
}

export default {
  install(app) {
    app.directive('permission', permission)
    app.directive('permission-role', permissionRole)
  }
}

